package com.example.myapplication.fragment;

import android.graphics.Color;

import com.example.myapplication.App;
import com.example.myapplication.R;
import com.example.myapplication.bean.Goods;
import com.example.myapplication.bean.OrderBean;
import com.example.myapplication.dao.GoodsDao;
import com.example.myapplication.database.GreenDaoManager;
import com.example.myapplication.database.OrderBeanDBUtils;
import com.example.myapplication.databinding.FragmentTongjiBinding;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.ArrayList;
import java.util.List;

import cn.project.base.baseui.BaseNormalFragment;

public class TongjiFragment extends BaseNormalFragment<FragmentTongjiBinding> {
    GoodsDao goodsDao;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tongji;
    }

    @Override
    protected void initData() {
        goodsDao = GreenDaoManager.getmInstance().getDaoSession().getGoodsDao();
        List<Goods> goodsLost = goodsDao.loadAll();
        if (goodsLost ==null || goodsLost.size() ==0){
            return;
        }
        //初始化饼状组件
        initChart();
        initBarChart();
    }
    private void initBarChart() {
        mBinding.chart1.getDescription().setEnabled(false); // 不显示描述
        mBinding.chart1.setExtraOffsets(20, 20, 20, 20); // 设置饼图的偏移量，类似于内边距 ，设置视图窗口大小
        setAxis(); // 设置坐标轴
        setLegend(); // 设置图例
        setDatas();  // 设置数据
    }

    private float getMoney(String state){
        List<OrderBean> orderBeanList =OrderBeanDBUtils.getInstance(getActivity()).getOrderByMerchatid(App.getInstance().merchant.getId(),state);
        if (orderBeanList ==null ||  orderBeanList.size() ==0){
            return  0;
        }
        float money = 0;
        for (int i = 0; i < orderBeanList.size(); i++) {
            money+=Float.parseFloat(orderBeanList.get(i).getPrice()) * Integer.parseInt(orderBeanList.get(i).getCount());
        }
        return money;
    }
    /**
     * 因为此处的 barData.setBarWidth(0.3f);，也就是说柱子的宽度是0.3f
     * 所以第二个柱子的值要比第一个柱子的值多0.3f，这样才会并列显示两根柱子
     */
    private void setDatas() {
        List<IBarDataSet> sets = new ArrayList<>();
        // 此处有两个DataSet，所以有两条柱子，BarEntry（）中的x和y分别表示显示的位置和高度
        // x是横坐标，表示位置，y是纵坐标，表示高度
        List<BarEntry> barEntries1 = new ArrayList<>();
        barEntries1.add(new BarEntry(0, getMoney("0")));
        barEntries1.add(new BarEntry(1, getMoney("1")));
        barEntries1.add(new BarEntry(2, getMoney("2")));
        BarDataSet barDataSet1 = new BarDataSet(barEntries1, "");
        barDataSet1.setValueTextColor(Color.RED); // 值的颜色
        barDataSet1.setValueTextSize(15f); // 值的大小
        barDataSet1.setColor(Color.parseColor("#1AE61A")); // 柱子的颜色
        barDataSet1.setLabel("销售额度统计"); // 设置标签之后，图例的内容默认会以设置的标签显示
        // 设置柱子上数据显示的格式
        barDataSet1.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                // 此处的value默认保存一位小数
                return value + "元";
            }
        });

        sets.add(barDataSet1);
        BarData barData = new BarData(sets);
        barData.setBarWidth(0.3f); // 设置柱子的宽度
        mBinding.chart1.setData(barData);
    }

    private void setLegend() {
        Legend legend =  mBinding.chart1.getLegend();
        legend.setFormSize(12f); // 图例的图形大小
        legend.setTextSize(15f); // 图例的文字大小
        legend.setDrawInside(true); // 设置图例在图中
        legend.setOrientation(Legend.LegendOrientation.VERTICAL); // 图例的方向为垂直
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); //显示位置，水平右对齐
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); // 显示位置，垂直上对齐
        // 设置水平与垂直方向的偏移量
        legend.setYOffset(55f);
        legend.setXOffset(30f);
    }

    private void setAxis() {
        // 设置x轴
        XAxis xAxis =  mBinding.chart1.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);  // 设置x轴显示在下方，默认在上方
        xAxis.setDrawGridLines(false); // 将此设置为true，绘制该轴的网格线。
        xAxis.setLabelCount(5);  // 设置x轴上的标签个数
        xAxis.setTextSize(15f); // x轴上标签的大小
        final String labelName[] = {"待发货", "已发货", "已卖出"};
        // 设置x轴显示的值的格式
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if ((int) value < labelName.length) {
                    return labelName[(int) value];
                } else {
                    return "";
                }
            }
        });
        xAxis.setYOffset(15); // 设置标签对x轴的偏移量，垂直方向

        // 设置y轴，y轴有两条，分别为左和右
        YAxis yAxis_right =  mBinding.chart1.getAxisRight();
        yAxis_right.setAxisMaximum(1200f);  // 设置y轴的最大值
        yAxis_right.setAxisMinimum(0f);  // 设置y轴的最小值
        yAxis_right.setEnabled(false);  // 不显示右边的y轴

        YAxis yAxis_left =  mBinding.chart1.getAxisLeft();
        yAxis_left.setAxisMaximum(1200f);
        yAxis_left.setAxisMinimum(0f);
        yAxis_left.setTextSize(15f); // 设置y轴的标签大小
    }
    private void initChart(){
        //是否用于百分比数据
        mBinding.chart.setUsePercentValues(true);
        mBinding.chart.getDescription().setEnabled(false);
        mBinding.chart.setExtraOffsets(5, 10, 5, 5);

        mBinding.chart.setDragDecelerationFrictionCoef(0.95f);

        //设置中间文本的字体
        //chart.setCenterTextTypeface(tfLight);
        //chart.setCenterText(generateCenterSpannableText());

        //是否绘制中心圆形区域和颜色
        mBinding.chart.setDrawHoleEnabled(true);
        mBinding.chart.setHoleColor(Color.WHITE);

        //是否绘制中心边透明区域
        mBinding.chart.setTransparentCircleColor(Color.WHITE);
        mBinding. chart.setTransparentCircleAlpha(110);

        //绘制中中心圆，和圆边的边框大小
        mBinding. chart.setHoleRadius(58f);
        mBinding. chart.setTransparentCircleRadius(61f);

        //是否绘制中心区域文字
        mBinding. chart.setDrawCenterText(true);

        //默认旋转角度
        mBinding. chart.setRotationAngle(0);
        //通过触摸启用图表的旋转
        mBinding.  chart.setRotationEnabled(true);
        //触摸进行高亮的突出设置
        mBinding. chart.setHighlightPerTapEnabled(true);

        //设置单位
        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        //添加选择侦听器
        mBinding. chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                //选中的扇页
            }

            @Override
            public void onNothingSelected() {
                //未选中的扇页
            }
        });

        //动画
        mBinding. chart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        //图例
        Legend l = mBinding.chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        //标签样式
        mBinding.chart.setEntryLabelColor(Color.WHITE);
        //chart.setEntryLabelTypeface(tfRegular);
        mBinding.chart.setEntryLabelTextSize(12f);

        //设置数据
        setData();
    }


    //设置数据
    private void setData() {
        //二维数据的二级数据
        ArrayList<PieEntry> entries = new ArrayList<>();
        //new PieEntry(数值，描述，图标icon)第一个
        entries.add(new PieEntry(OrderBeanDBUtils.getInstance(getActivity()).getOrderByMerchatid(App.getInstance().merchant.getId(),"0").size(), "待发货", null));
        entries.add(new PieEntry(OrderBeanDBUtils.getInstance(getActivity()).getOrderByMerchatid(App.getInstance().merchant.getId(),"1").size(), "已发货", null));
        entries.add(new PieEntry(OrderBeanDBUtils.getInstance(getActivity()).getOrderByMerchatid(App.getInstance().merchant.getId(),"2").size(), "已收获", null));

        //二维数据的一级数据
        PieDataSet dataSet = new PieDataSet(entries, "销售统计");
        //数据配置，是否绘制图标
        dataSet.setDrawIcons(false);
        //扇页之间的空白间距
        dataSet.setSliceSpace(3f);
        //图标偏移
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        //添加颜色集合，
        ArrayList<Integer> colors = new ArrayList<>();
        //colors.add(ColorTemplate.LIBERTY_COLORS[0]);
        colors.add(Color.parseColor("#3790A2"));
        colors.add(Color.parseColor("#37F0A2"));
        colors.add(Color.parseColor("#49DBEE"));
//        colors.add(Color.parseColor("#43C088"));
        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        //设置图表数据
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        //data.setValueTypeface(tfLight);
        mBinding.chart.setData(data);

        //撤消所有高光
        mBinding.chart.highlightValues(null);

        //刷新图表UI
        mBinding. chart.invalidate();
    }
}
